<template>
  <div class="app-container">
    <el-button v-if="checkPermission(permissionRoles.gift_code_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加礼包码</el-button>
    <el-button class="filter-item" type="success" icon="el-icon-search" @click="handleViewCode">查询礼包码</el-button>

    <el-table v-loading="listLoading" :data="list" class="mt-15" height="660" border>
      <el-table-column label="批次ID" prop="id" width="60px" align="center"></el-table-column>
      <el-table-column label="礼包名称" prop="gift_name" width="100px" align="center"></el-table-column>
      <el-table-column label="礼包内容" prop="items_str" width="500px" align="center"></el-table-column>
      <el-table-column label="类型" align="center" width="60px">
        <template slot-scope="{row}">
          <span v-if="row.type === 1">普通码</span>
          <span v-else>指定码</span>
        </template>
      </el-table-column>
      <el-table-column label="创建时间" prop="create_dt" width="140px" align="center"></el-table-column>
      <el-table-column label="使用限制" prop="times" width="90px" align="center"></el-table-column>
      <el-table-column label="礼包码" prop="code" align="center"></el-table-column>
      <el-table-column label="礼包码数量" prop="num" width="70px" align="center"></el-table-column>
      <el-table-column label="已使用数量" prop="used_num" width="70px" align="center"></el-table-column>
      <el-table-column label="渠道限制" prop="cname" width="90px" align="center"></el-table-column>
      <el-table-column label="操作" fixed="right" width="90px" align="center">
        <template slot-scope="{row}">
          <el-button v-if="checkPermission(permissionRoles.gift_code_download)" type="text" size="small" :loading="downloadLoading" @click="handleExport(row)">导出</el-button>
          <el-button v-if="checkPermission(permissionRoles.gift_code_del)" type="text" size="small" title="删除" @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" :title="textMap[dialogType]" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="礼包" prop="gift_id">
          <el-select v-model="dataForm.gift_id" class="defaut-input" filterable clearable>
            <el-option
              v-for="item in giftList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="dataForm.type" class="defaut-input" @change="changeType(dataForm.type)">
            <el-option label="普通码" value="1" />
            <el-option label="指定码" value="2" />
          </el-select>
        </el-form-item>
        <el-form-item v-if="codeVisible" label="指定码">
          <el-input v-model="dataForm.code" class="defaut-input" placeholder="请输入指定码" />
        </el-form-item>
        <el-form-item v-if="numVisible" label="数量">
          <el-input v-model="dataForm.num" class="defaut-input" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="使用限制">
          <el-input v-model="dataForm.times" class="defaut-input" placeholder="请输入使用限制" />
        </el-form-item>
        <el-form-item label="渠道限制">
          <el-select v-model="dataForm.cid" class="defaut-input" filterable clearable>
            <el-option
              v-for="item in channelList"
              :key="item.id"
              :label="item.name"
              :value="item.cid"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <el-dialog :visible.sync="codeDialogVisible" title="查询礼包码" :close-on-click-modal="false" width="80%" :fullscreen="true">
      <el-select v-model="codeListQuery.gift_id" filterable clearable class="filter-item" style="width: 120px;" placeholder="礼包">
        <el-option
          v-for="(item, index) in giftList"
          :key="index"
          :label="item.name"
          :value="item.id"
        />
      </el-select>
      <el-input v-model="codeListQuery.code" class="filter-item" placeholder="礼包码" style="width: 120px;"></el-input>
      <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-table v-loading="codeListLoading" :data="codeList" class="mt-15" height="720" border>
        <el-table-column label="礼包码" prop="code" width="120px" align="center"></el-table-column>
        <el-table-column label="礼包名称" prop="gift_name" align="center"></el-table-column>
        <el-table-column label="礼包内容" prop="items_str" width="350px" align="center"></el-table-column>
        <el-table-column label="类型" align="center">
          <template slot-scope="{row}">
            <span v-if="row.type === 1">普通码</span>
            <span v-else>指定码</span>
          </template>
        </el-table-column>
        <el-table-column label="生成时间" prop="create_dt" width="170px" align="center"></el-table-column>
        <el-table-column label="批次ID" prop="config_id" align="center"></el-table-column>
        <el-table-column label="使用限制" prop="times" align="center"></el-table-column>
        <el-table-column label="已使用次数" prop="used_times" align="center"></el-table-column>
        <el-table-column label="剩余次数" prop="residue" align="center"></el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="{row}">
            <span v-if="row.status === 1">已使用</span>
            <span v-else>未使用</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="ctotal>0" :total="ctotal" :page.sync="codeListQuery.page" :limit.sync="codeListQuery.limit" @pagination="getCodeList" />

    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>
<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import { getGiftList, getGiftCodeConfigList, handleGiftCodeConfig, deleteGiftCodeConfig, getGiftCodeList } from '@/api/operator'
import Pagination from '@/components/Pagination'
import { deepClone } from '@/utils'
import { getChannelList } from '@/api/ops'

const defaultItem = {
  id: '',
  gift_id: '',
  type: '1',
  code: '',
  num: '',
  times: '1',
  cid: ''
}
export default {
  name: 'GiftCode',
  components: { Pagination },
  data() {
    return {
      listLoading: false,
      downloadLoading: false,
      codeListLoading: false,
      permissionRoles: this.$store.state.user.permissionRoles,
      dataForm: Object.assign({}, defaultItem),
      rules: {
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      codeListQuery: {
        gift_id: '',
        code: '',
        page: 1,
        limit: 200
      },
      total: 0,
      ctotal: 0,
      list: [],
      codeList: [],
      expCodeList: [],
      giftList: [],
      channelList: [],
      dialogVisible: false,
      codeDialogVisible: false,
      codeVisible: false,
      numVisible: true,
      dialogType: 'new',
      textMap: {
        new: '新增',
        edit: '编辑'
      }
    }
  },
  computed: {
  },
  created() {
    this.getList()
  },
  methods: {
    checkPermission,
    async getList() {
      this.listLoading = true
      getGiftCodeConfigList(this.listQuery).then(response => {
        this.list = response.data.items
        this.total = response.data.total
        this.listLoading = false
      })
    },
    async getChannelList() {
      const res = await getChannelList()
      this.channelList = res.data.items
    },
    async getGiftList() {
      const res = await getGiftList()
      this.giftList = res.data.items
    },
    changeType(type) {
      if (type === '1') {
        this.numVisible = true
        this.codeVisible = false
      } else {
        this.numVisible = false
        this.codeVisible = true
      }
    },
    handleAdd() {
      this.getChannelList()
      this.getGiftList()
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogType = 'new'
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleExport(row) {
      this.downloadLoading = true
      getGiftCodeList({ config_id: row.id, limit: 10000000 }).then(response => {
        this.expCodeList = response.data.items
        import('@/vendor/Export2Excel').then(excel => {
          const tHeader = ['礼包码', '批次ID', '礼包名称', '礼包内容', '渠道', '状态']
          const filterVal = ['code', 'id', 'gift_name', 'items_str', 'cid', 'status_str']
          const data = this.formatJson(filterVal)
          excel.export_json_to_excel({
            header: tHeader,
            data,
            filename: row.gift_name
          })
          this.downloadLoading = false
        })
      })
    },
    formatJson(filterVal) {
      return this.expCodeList.map(v => filterVal.map(j => {
        return v[j]
      }))
    },
    handleEdit(row) {
      if (row.items === null) row.items = ''
      if (Array.isArray(row.items) === false) {
        if (row.items === '') {
          row.items = [{ id: '', num: '' }]
        } else {
          const items = row.items.split(',')
          const a = []
          for (let i = 0; i < items.length; i++) {
            const o = { id: '', num: '' }
            const e = items[i].split('*')
            o.id = parseInt(e[0])
            o.num = parseInt(e[1])
            a[i] = o
          }
          row.items = a
        }
      }
      if (row.title.substring(row.title.length - 3, row.title.length) === '...') {
        row.title = row.title.substring(0, row.title.length - 3)
      }
      if (row.content.substring(row.content.length - 3, row.content.length) === '...') {
        row.content = row.content.substring(0, row.content.length - 3)
      }

      this.getItemConfig()
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.dataForm = deepClone(row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          handleGiftCodeConfig(this.dataForm).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getList()
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    handleDelete(row) {
      this.$confirm('你确定要删除此行数据吗?', '删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteGiftCodeConfig(row.id)
          this.getList()
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        })
        .catch(err => { console.error(err) })
    },
    handleViewCode() {
      this.getGiftList()
      this.codeDialogVisible = true
    },
    async getCodeList() {
      this.codeListLoading = true
      getGiftCodeList(this.codeListQuery).then(response => {
        this.codeList = response.data.items
        this.ctotal = response.data.total
        this.codeListLoading = false
      })
    },
    handleFilter() {
      this.getCodeList()
    }
  }
}
</script>

<style>
.el-tabs__header {
  margin: 0px;
}
</style>
